<?php
/*
 * Created on Feb 5, 2009
 * @author: ANH
 * @PARAM rtype is rootType: example: caves is type then attraction is rtype
 * @filesource: modules/product/controllers/PlaceController.php
 */
class Product_MasterController extends Clu_Controller_Action_Master
{
	public function init()
	{
		$this->m = new product_Model_Product();
		parent::init();
	}
	
    public function listAction() 
    {
       	$sess = new Zend_Session_Namespace(CLU_NS);
        $this->viewParams['form'] = new product_Form_Product();
        $actionUrl = $this->hvnUrl(array('module' => 'product', 'action'=>'new'), 'nocontroller');
        $this->viewParams['form']->cluBuild(array('action' => 'new', 'action_url' => $actionUrl, 
							  'userPermissions' => $sess->userPermissions, 
							  'language' => $sess->viewLang ));
     	$this->viewParams['errorMessage'] = '';
        $formName = 'product_Form_Product';
        $data = $this->_request->getParams();
		//if valid data     
        if ($this->_request->isPost() && $this->viewParams['form']->isValid($_POST)) 
	    {
	        $db = $this->db;
	        $db->beginTransaction();
            try 
            {
                 $this->m->insertRaw($data,false);
                 $db->commit();
            }
            catch (Exception $e)
            {
                $db->rollBack();
                $this->viewParams['errorMessage'] = $e->getMessage() . "<br/>". t(69);
            }
		}

    }
  

    public function editAction()
    {
        $productId = $this->_request->getParam('id');
        $userId = $this->_request->getParam('user_id');
        if (!$p = $this->m->findByPrimary($productId))
        {
        	$this->viewParams['errorMessage'] = t(725);
        }

        $this->viewParams['form'] = new product_Form_Product();
        $actionUrl = $this->hvnUrl(array('module' => 'product', 'action'=>'edit'), 'nocontroller');
        $this->viewParams['form']->cluBuild(array('action' => 'edit', 'action_url' => $actionUrl));
        if (!$this->_request->isPost())
        {
            $this->viewParams['form']->populateFormData($p);
        }
        else if ( $this->viewParams['form']->isValid($_POST))
        {
	    	$data = $this->_request->getParams();
		    if(! $this->m->saveRaw($p, $data, $productId, array('do_validate' => false)))
		    	return false;	
		    else
		    {
		    	$sess = new Zend_Session_Namespace(CLU_NS);
		    	$user_Id = $data['user_id'];
		    	$this->_helper->redirector->gotoUrl($sess->viewLang .'/user/account/list-product?id='.$user_Id); //todo
		    	return;
		    }
        }
        $this->viewParams['user_id'] = $userId;
        $this->viewParams['id'] = $productId;
    }
    
	public function uploadImgProductAction()
    {
        $products = $this->_request->getParams();
		$product =  $this->m->findByPrimary($products['id']);
		$productId = $products['id'];
		$userId = $products['poster_id'];
	   if (!$product)
	   {
   			$this->renderError(null, __("Could not find the product"));
   			return;
	   }
			 if ($this->_request->isPost())
			 {
				 $fileName = $_FILES['myFile']['name'];
				 if($_FILES['myFile']['name']){
					$ustoreDir = APP_PATH."/public/ustore/$userId/images/original/product/$productId/";
					if (!file_exists($ustoreDir))
							mkdir($ustoreDir, 0777  , true);
					$ufilesDir = APP_PATH."/public/ufiles/$userId/images/original/product/$productId/" ;
					if (!file_exists($ufilesDir))
								mkdir($ufilesDir, 0777  , true);
					$fileName = $_FILES['myFile']['name'];
					//make sure the file name is unique
					$targetFile = $ustoreDir . $fileName;
					$j = 1;
					while(file_exists($targetFile))
					{
						$fileName = $j . "_" . $_FILES['myFile']['name'];
						$targetFile = $ustoreDir . $fileName;	
						$j++;
					};
					move_uploaded_file($_FILES['myFile']['tmp_name'],$targetFile);
					//require_once APP_PATH."/library/common.php";
					$watermarkDir = APP_PATH."/public/watermark/";
					// now generate copies
					//TODO: if editors, then do watermark
					$ret = generate_image_copies ("ustore", $ustoreDir,$fileName, $watermarkDir, null, null, $userId, false); //with wm		
					if ($ret == false)
					{
						//remove the uploaded files
				    	unlink ($targetFile);
			        }
				   else
				   {
	                	$image = str_replace(APP_PATH, "", $targetFile);
	                	
                		if(isset($product->images))
                		{
		                	$metadata = str_replace("/public/ustore/", "/public/ufiles/", $image) . ';' . $product->images;
                		}
			        	$images['images'] = $metadata;      
			        	try 
			        	{
			        		$product->setFromArray($images);
			        		$product->save();
			        		$sess = new Zend_Session_Namespace(CLU_NS);
			        		$this->_helper->redirector->gotoUrl($sess->viewLang .'/user/account/list-product?id='.$userId); //todo
		    				return;
			        	}
			        	catch (Exception $e)
			        	{
			        		die($e->getMessage());
			        	}
				    }
				}
		   }
    }  
}
?>
